const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const cors = require('cors')
const mysql = require('mysql2/promise')
const app = express()
const port = 3000

// 创建数据库连接
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'product_shopping'
}
let pool;
(async () => {
  try {
    pool = await mysql.createPool(dbConfig) // 创建连接池

    process.on('SIGINT', async () => {
      await pool.end() // 关闭连接池
      process.exit(0) // 退出程序
    })
    process.on('SIGIERM', async () => {
      await pool.end() // 关闭连接池
      process.exit(0) // 退出程序
    })

    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`)
    })
  } catch (error) {
    console.log('连接失败')
    process.exit(1) // 退出程序
  }
})()


app.use(cors())
// 解析 JSON 的中间键
app.use(express.json())

app.get('/', (req, res) => {
  res.send('Hello World!')
})

// 文件处理
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    // 时间戳 + 图片名字
    cb(null, Date.now() + path.extname(file.originalname))
  }
})
const upload = multer({ storage: storage })

// 上传图片接口
app.post('/api/upload', upload.single('image'), (req, res) => {
  // 拿到上传的文件
  const file = req.file
  if (!file) {
    return res.status(400).json({
      code: 400,
      message: '上传失败'
    })
  } else {
    // 地址变为绝对地址,直接访问
    const absolutePath = `http://127.0.0.1:${port}/uploads/${file.filename}`
    res.json({
      code: 200,
      message: '上传成功',
      file: {
        "originalname": file.originalname, // 原始文件名
        "mimetype": file.mimetype, // 文件类型
        "filename": file.filename, // 存储文件名
        "path": absolutePath, // 文件路径
        "size": file.size // 文件大小(字节)
      }
    })
  }

})
// 访问图片的路由
app.get('/uploads/:filename', (req, res) => {
  const filename = req.params.filename
  const filePath = path.join(__dirname, 'uploads', filename)
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      return res.json({
        code: 404,
        message: '文件不存在'
      })
    }
    // 发送文件给前端
    res.sendFile(filePath)
  })
})
// 创建新增产品接口
app.post('/api/products', async (req, res) => {
  const product = req.body
  console.log(req.body, '-')
  const { productname, nuclear, weight, price, description, image } = product

  try {
    const connection = await pool.getConnection()
    console.log(productname, nuclear, weight, price, description, image)
    const [rows] = await connection.execute('INSERT INTO products (name,nuclear,weight,price,description,imgurl) VALUES (?,?,?,?,?,?)', [productname, nuclear, weight, price, description, image])

    connection.release()
    res.json({
      code: 200,
      message: '新增成功',
      data: { id: rows.insertId, ...product }
    })
  } catch (error) {
    console.log(error, '--error')
  }
})

